#!/bin/bash
# Rust 安装和 moparse 编译一键脚本

set -e

echo "=============================================="
echo "Rust 版本 moparse 完整安装和编译脚本"
echo "=============================================="
echo ""

# 颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
print_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
print_error() { echo -e "${RED}[ERROR]${NC} $1"; }
print_step() { echo -e "${BLUE}[STEP]${NC} $1"; }

# 步骤 1: 检查 Rust
print_step "1. 检查 Rust 是否已安装"

if [ -f "$HOME/.cargo/env" ]; then
    source "$HOME/.cargo/env"
fi

if command -v rustc &> /dev/null; then
    print_info "✓ Rust 已安装"
    rustc --version
    cargo --version
    RUST_INSTALLED=1
else
    print_warn "✗ Rust 未安装"
    RUST_INSTALLED=0
fi

echo ""

# 步骤 2: 安装 Rust（如果需要）
if [ $RUST_INSTALLED -eq 0 ]; then
    print_step "2. 安装 Rust"
    print_info "正在下载并安装 Rust..."
    
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
    
    if [ $? -eq 0 ]; then
        print_info "✓ Rust 安装成功"
        source "$HOME/.cargo/env"
        rustc --version
        cargo --version
    else
        print_error "✗ Rust 安装失败"
        exit 1
    fi
else
    print_step "2. 跳过 Rust 安装（已安装）"
fi

echo ""

# 步骤 3: 安装系统依赖
print_step "3. 检查系统依赖"

if ! command -v gcc &> /dev/null; then
    print_warn "GCC 未安装，正在安装开发工具..."
    sudo yum groupinstall "Development Tools" -y
else
    print_info "✓ GCC 已安装"
fi

echo ""

# 步骤 4: 进入项目目录
print_step "4. 进入项目目录"
cd /home/apachee/trunk/Crystal/CrystalFlowAnalyzer/modb/moparse-rs
print_info "当前目录: $(pwd)"

echo ""

# 步骤 5: 检查项目文件
print_step "5. 检查项目文件"

check_file() {
    if [ -f "$1" ]; then
        print_info "✓ $1"
        return 0
    else
        print_error "✗ $1 不存在"
        return 1
    fi
}

check_file "Cargo.toml" || exit 1
check_file "build.rs" || exit 1
check_file "src/main.rs" || exit 1
check_file "src/lib.rs" || exit 1
check_file "src/parser.rs" || exit 1

# 检查 proto 文件
if [ -f "../src/modb.proto" ]; then
    print_info "✓ ../src/modb.proto"
else
    print_error "✗ ../src/modb.proto 不存在"
    print_warn "请确保 C++ 版本的 modb.proto 文件存在"
    exit 1
fi

echo ""

# 步骤 6: 编译 Debug 版本
print_step "6. 编译 Debug 版本"
print_info "开始编译（首次编译会下载依赖，可能需要几分钟）..."

if cargo build 2>&1 | tee /tmp/cargo_build_output.log; then
    print_info "✓ Debug 版本编译成功！"
    
    if [ -f "target/debug/moparse" ]; then
        echo ""
        print_info "可执行文件信息:"
        ls -lh target/debug/moparse
    fi
else
    print_error "✗ 编译失败"
    echo ""
    echo "===== 错误日志 (最后 50 行) ====="
    tail -50 /tmp/cargo_build_output.log
    echo "=================================="
    exit 1
fi

echo ""

# 步骤 7: 基本测试
print_step "7. 运行基本测试"

print_info "测试 1: 版本信息"
./target/debug/moparse --version

echo ""

print_info "测试 2: 帮助信息"
./target/debug/moparse --help | head -15

echo ""

# 步骤 8: 功能测试
print_step "8. 功能测试"

TEST_V_FILE="../tests/counter_full.v"
if [ -f "$TEST_V_FILE" ]; then
    print_info "使用测试文件: $TEST_V_FILE"
    
    print_info "测试解析功能..."
    if ./target/debug/moparse parse -v "$TEST_V_FILE" -o /tmp/test_rust.modb 2>&1; then
        print_info "✓ 解析成功"
        
        if [ -f "/tmp/test_rust.modb" ]; then
            print_info "输出文件: /tmp/test_rust.modb ($(ls -lh /tmp/test_rust.modb | awk '{print $5}'))"
            
            print_info "测试显示功能..."
            ./target/debug/moparse show -s /tmp/test_rust.modb | head -20
            
            print_info "清理测试文件..."
            rm -f /tmp/test_rust.modb
        fi
    else
        print_warn "解析测试失败（可能功能未完全实现）"
    fi
else
    print_warn "测试文件不存在: $TEST_V_FILE"
fi

echo ""

# 步骤 9: 编译 Release 版本（可选）
print_step "9. 编译 Release 版本"
echo ""
read -p "是否编译优化的 Release 版本？ (y/N): " -n 1 -r
echo ""

if [[ $REPLY =~ ^[Yy]$ ]]; then
    print_info "开始编译 Release 版本..."
    
    if cargo build --release 2>&1 | tee /tmp/cargo_release_output.log; then
        print_info "✓ Release 版本编译成功！"
        
        if [ -f "target/release/moparse" ]; then
            echo ""
            print_info "可执行文件信息:"
            ls -lh target/release/moparse
            
            if command -v ldd &> /dev/null; then
                echo ""
                print_info "动态库依赖:"
                ldd target/release/moparse
            fi
        fi
    else
        print_error "✗ Release 编译失败"
        tail -50 /tmp/cargo_release_output.log
    fi
else
    print_info "跳过 Release 编译"
fi

echo ""
echo "=============================================="
echo "编译完成！"
echo "=============================================="
echo ""
print_info "可执行文件:"
echo "  Debug:   target/debug/moparse"
[ -f "target/release/moparse" ] && echo "  Release: target/release/moparse"
echo ""
print_info "使用示例:"
echo "  ./target/debug/moparse --help"
echo "  ./target/debug/moparse parse -v input.v -o output.modb"
echo "  ./target/debug/moparse show -s output.modb -v"
echo ""
print_info "详细文档:"
echo "  README.md"
echo "  BUILD_TEST_GUIDE.md"
echo "  CENTOS7_DEPLOYMENT.md"
echo ""
